import subprocess
import time

from django.core.cache import caches
from django.db import connection
from django.shortcuts import render

from app.model.table_goods import TableGoods
from app.service import web_socket, git as git_serv
from app.service.goods_barcode import get_shop_goods_id_by_barcode, save_shop_goods_barcode
from libs import time_helper, common
from libs.common import success, get_ts, error
from libs.db import DB


def timestamp(request):
    ts = int(time.time())
    datetime_str = time_helper.ts_to_time_str(ts, time_format='%Y-%m-%d %H:%M:%S')
    ip = common.get_ip(request)
    return success(timestamp=ts, datetime=datetime_str, ip=ip)


def bar(request):
    return success({'hello': 'world'})


def git(request):
    pwd = request.GET.get('PASS', default='')
    bak = request.GET.get('bak', default='')
    bak_flag = False
    if bak == 'bak':
        bak_flag = True
    if request.META['HTTP_HOST'] == '8.134.70.157:8800':
        if pwd != '7095':
            return error('invalid password', tip=[
                'need pwd',
                'cmd 1 to force reset',
            ])
        bak_flag = True
    if bak_flag:
        ymd = time_helper.ts_to_time_str(time_format='%y%m%d%H%M%S')
        bak_cmd = 'tar zcf /www/app_tar/{}.tar.gz ./ --exclude=./logs'.format(ymd)
        p = subprocess.Popen(bak_cmd, shell=True, stdout=subprocess.DEVNULL)
        p.communicate()
    cmd = request.GET.get('cmd', default='')
    lines = []
    if cmd != '0':
        if cmd == '1':
            cmd = 'git fetch --all && git reset --hard origin/master'
        else:
            cmd = 'git pull'
        sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        out, err = sp.communicate()
        for line in out.splitlines():
            lines.append(str(line, 'utf-8'))
    ver_hash, create_at = git_serv.get_local_last_ver()
    if ver_hash != '':
        fs_cache = caches['fs']
        git_update_versions = fs_cache.get('git_update_versions')
        if git_update_versions is None:
            git_update_versions = []
        elif len(git_update_versions) >= 30:
            git_update_versions.pop(0)
        has_hash = 0
        for ver_info in git_update_versions:
            vh = ver_info.get('hash')
            if vh == ver_hash:
                has_hash = 1
                break
        if has_hash == 0:
            git_update_versions.append({'hash': ver_hash, 'create_at': create_at})
            fs_cache.set('git_update_versions', git_update_versions, None)
    return success(lines)


def git_local_ver(request):
    cmd = 'git log --pretty=format:"%h %cd (%cr)" -1'
    sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    out, err = sp.communicate()
    lines = []
    for line in out.splitlines():
        lines.append(str(line, 'utf-8'))
    return success(lines)


def git_update_ver_list(request):
    git_update_versions = caches['fs'].get('git_update_versions')
    return success(git_update_versions)


def nav(request):
    return render(request, 'dev/nav.html')


def socket_test(request):
    return render(request, 'dev/socket.html')


def send_msg(request):
    yuan = request.GET.get('yuan', default='100000000')
    cashier_id = request.GET.get('cashier_id', default='1')
    msg = '支付宝到账{}元'.format(yuan)
    web_socket.notice_payment(cashier_id, msg)
    return success(msg)


def sync_goods_barcode(request):
    do_next = True
    page = 1
    size = 100
    while do_next:
        from_num = (page - 1) * size
        to_num = from_num + size
        goods_rows = TableGoods.objects.filter(barcode__isnull=False, shoper_id=26).all()[from_num:to_num]
        row_num = len(goods_rows)
        page = page + 1
        if row_num == 0:
            do_next = False
        else:
            for goods_row in goods_rows:
                alias_goods_id = get_shop_goods_id_by_barcode(goods_row.shoper_id, goods_row.id)
                if alias_goods_id == 0 and goods_row.barcode != '':
                    save_shop_goods_barcode(goods_row.shoper_id, goods_row.id, goods_row.barcode)
    return success()


def sync_barcode_archives(request):
    do_next = True
    page = 1
    size = 100
    now = get_ts()
    with connection.cursor() as cursor:
        db = DB('cs_barcodes', conn=cursor)
        while do_next:
            from_num = (page - 1) * size
            to_num = from_num + size
            goods_rows = TableGoods.objects.filter(device_goods_id__isnull=False).all()[from_num:to_num]
            row_num = len(goods_rows)
            page = page + 1
            if row_num == 0:
                do_next = False
            else:
                for goods_row in goods_rows:
                    barcode_data = {
                        'goods_name': goods_row.goods_name,
                        'price': goods_row.usdt_price,
                        'cost_price': goods_row.cost_price,
                        'spec': '',
                        'unit': goods_row.unit,
                        'created': now,
                    }
                    barcode = ''
                    if len(goods_row.barcode) > 0:
                        barcode = goods_row.barcode
                    elif type(goods_row.device_goods_id) is str and len(goods_row.device_goods_id) > 0:
                        pos = goods_row.device_goods_id.find('_')
                        if pos > 0:
                            barcode = goods_row.device_goods_id[pos + 1:]
                    if len(barcode) == 13:
                        flag = barcode[0:2]
                        barcode_data.update({'barcode': barcode, 'flag': flag})
                        print(db.insert(barcode_data))
    return success()
